package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 虎哥
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    private final CategoryBrandService categoryBrandService;

    public BrandServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(String key, Integer page, Integer rows) {
        // 健壮性判断
        boolean isKeyExists = StringUtils.isNotBlank(key);
        // 查询
        Page<Brand> info = query()
                // 条件： WHERE `name` LIKE "%h%" OR letter = 'h'
                .like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                // 分页： LIMIT 0, 25
                .page(new Page<Brand>(page, rows));
        // 解析分页结果
        List<Brand> list = info.getRecords();
        // 转换DTO
        List<BrandDTO> dtoList = BrandDTO.convertEntityList(list);
        // 封装分页结果
        return new PageDTO<>(info.getTotal(), info.getPages(), dtoList);
    }

    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long id) {
        List<Brand> list = getBaseMapper().queryByCategoryId(id);
        return BrandDTO.convertEntityList(list);
    }

    @Transactional
    @Override
    public void saveBrand(BrandDTO brandDTO) {
        // DTO转换
        Brand brand = brandDTO.toEntity(Brand.class);
        // 新增品牌
        save(brand);
        Long brandId = brand.getId();

        // 拿到分类id
        List<Long> categoryIds = brandDTO.getCategoryIds();
        // 组织中间表集合
        List<CategoryBrand> list = new ArrayList<>();
        for (Long categoryId : categoryIds) {
            // 创建中间表对象
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            list.add(categoryBrand);
        }

        /*List<CategoryBrand> list = brandDTO.getCategoryIds()
                .stream()
                .map(cid -> CategoryBrand.of(cid, brandId))
                .collect(Collectors.toList());*/

        // 新增中间表
        categoryBrandService.saveBatch(list, list.size());
    }
}
